<?php
class Controller_Weixin extends Controller
{
    function __construct($req, $res)
    {
        parent::__construct($req, $res);
    }

    public function action_index ()
    {
        $token = 'm4eeee';
        $isvalid = FALSE;

        if (isset($_GET['echostr']))
            $isvalid = TRUE;

        $wechatObj = new Wechat($token, $isvalid);
        $wechatObj->index();
    }

    public function action_menu()
    {
        $we = new Wechat('m4eeee', FALSE);
        $we->createMenu();
    }

    public function action_bind()
    {
        $post = $this->request->post();
        if (! empty($post))
        {
            $this->bind($post);
            return;
        }

        $query = $this->request->query();
        $weixinid = Arr::get($query, 'wid', NULL);
        if (empty($weixinid))
            throw new Exception_Warn("无效ID");

        echo <<<EOF
<!DOCTYPE html>
<html>
<head>
<title>方寸掌悦-微信账户绑定</title>
<meta http-equiv="Content-type" content="text/html; charset="utf-8"/>
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<style type="text/css">
body, form { font-size: 24px; }
body { text-align: center; }
form input { text-align: left;}
</style>
</head>
<body>
<div>
    <form action="" method="POST">
        <input type="hidden" name="weixinid" value="$weixinid">
        <h3>方寸掌悦账户</h3>
        <p><input type="text" name="passport"></p>
        <h3>方寸掌悦密码</h3>
        <p><input type="text" name="password"></p>
        <p><input type="submit" name="submit"></p>
    </form>
</div>
</body>
</html>
EOF;
    }

    private function bind($post)
    {
        $passport = Arr::get($post, 'passport');
        $password = Arr::get($post, 'password');
        $weixin   = Arr::get($post, 'weixinid');
        try {
            
            Wechat::bind_passport($passport, $password, $weixin);
            echo "绑定账户成功!";
        }
        catch (Exception $e)
        {
            echo "绑定失败，点击<a href=\"/weixin/bind\">重新绑定</a>";
        }

    }
}

